package com.work.demo.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.work.demo.entity.UserDto;
import com.work.demo.utils.UserThradLocal;
import org.apache.catalina.connector.Response;
import org.apache.catalina.connector.ResponseFacade;
import org.apache.tomcat.util.http.MimeHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Collection;

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/test")
    public UserDto test(){
        return UserThradLocal.getCurrentUser();
    }

    @GetMapping("/res")
    public String testRes(HttpServletRequest request, HttpServletResponse response){

        response.setHeader("Set-Cookie", "12345");
        Collection<String> headers = response.getHeaders("Set-Cookie");
        if (CollectionUtil.isNotEmpty(headers)){
            deleteSetCookie(response);
        }
        return "123";
    }

    private void deleteSetCookie(HttpServletResponse response){
        ;
        try {
            System.out.println(response.getHeaderNames());
            Field declaredField = ResponseFacade.class.getDeclaredField("response");
            declaredField.setAccessible(true);
            Response resp = (Response) declaredField.get(response);
            org.apache.coyote.Response coyoteResponse = resp.getCoyoteResponse();
            MimeHeaders mimeHeaders = coyoteResponse.getMimeHeaders();
            mimeHeaders.removeHeader("Set-Cookie");//删除你要删除的header
            System.out.println("处理之后的headers" + response.getHeaderNames());
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }
}
